package org.movee.spring.data.hugegraph.repository.query;

import org.movee.spring.data.hugegraph.convert.HugeConverter;
import org.movee.spring.data.hugegraph.mapping.HugePersistentEntity;
import org.movee.spring.data.hugegraph.mapping.HugePersistentProperty;
import org.springframework.data.repository.core.support.PersistentEntityInformation;
import org.springframework.util.Assert;

import javax.annotation.Nullable;

public class MappingHugeEntityInformation<T, ID>
        extends PersistentEntityInformation<T, ID> implements HugeEntityInformation<T, ID> {


    private final HugePersistentEntity<T> persistentEntity;

    private final HugeConverter converter;

    public MappingHugeEntityInformation(final HugePersistentEntity<T> entity, final HugeConverter converter) {

        super(entity);

        this.persistentEntity = entity;
        this.converter = converter;

    }


    /* (non-Javadoc)
     * @see org.springframework.data.repository.core.EntityInformation#getId(java.lang.Object)
     */
    @SuppressWarnings("unchecked")
    @Override
    @Nullable
    public ID getId(T entity) {

        Assert.notNull(entity, "Entity must not be null");

        HugePersistentProperty idProperty = this.persistentEntity.getIdProperty();

        return idProperty != null ? (ID) this.persistentEntity.getIdentifierAccessor(entity).getIdentifier()
                : (ID) converter.getId(entity, persistentEntity);
    }

    /* (non-Javadoc)
     * @see org.springframework.data.repository.core.EntityInformation#getIdType()
     */
    @SuppressWarnings("unchecked")
    @Override
    public Class<ID> getIdType() {

        if (this.persistentEntity.getIdProperty() != null) {
            return (Class<ID>) this.persistentEntity.getRequiredIdProperty().getType();
        }

        // TODO: 抛出异常
        return null;
    }

}
